package com.zn.websocket.server;

import com.alibaba.fastjson.JSONObject;
import com.zn.entity.OptionTradingContract;
import com.zn.entity.OptionTradingGoods;
import com.zn.service.MdInfoService;
import com.zn.util.Constant;
import com.zn.util.DateUtils;
import com.zn.vo.Response;
import com.zn.web.rpc.TradeDateCall;
import com.zn.websocket.group.ChannelGroups;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * Created by admintrator on 2018/11/13.
 */
@Component
public class ChannelGroupsServer {
    private static final Logger LOGGER = LoggerFactory.getLogger(ChannelGroupsServer.class);

    @Autowired
    RedisTemplate<String,String> redisTemplate;
    @Autowired
    MdInfoService mdInfoService;
    @Autowired
    private TradeDateCall tradeDateCall;

    public void Initialization(){

        try {
            //启动时初始化redis初始数据，初始化通道
            List<String> str = new ArrayList<>();
            Map<Object, Object> mapTarget = redisTemplate.opsForHash().entries(Constant.TARGET_CODE_LIST);
            if (mapTarget.size() > 0) {
                for (Object mapKey : mapTarget.keySet()) {
                    String key = mdInfoService.checkRedisKey(Constant.INSTRUMENT_MONTH_SET + mapKey.toString());
                    Set<String> targetDateSet = redisTemplate.opsForSet().members(key);
                    for (String ym : targetDateSet) {
                        if (!str.contains(ym)) {
                            str.add(ym);
                        }
                    }
                }
            }else {//如果redis中么有，从数据库中获取基础数据
                List<OptionTradingContract> optionTradingContractList = mdInfoService.selectIsTrading();
                for (OptionTradingContract record : optionTradingContractList){
                    str.add(record.getContractMonthName());
                }
            }
            ChannelGroups.Initialization(str);

            //初始化交易商品基础信息和交易日判断信息
            List<OptionTradingGoods> optionTradingGoodsList = mdInfoService.findtradingGoodsCodeAll();
            for (OptionTradingGoods optionTradingGoods : optionTradingGoodsList) {
                //获取最后一个交易时间段，加上5分钟。因：交易结束前五分钟不能在开仓
                String[] tradingTimes = optionTradingGoods.getTradingTime().split("\\|");
                String[] timeSlot = tradingTimes[tradingTimes.length - 1].split("-");
                String nowDateStr = DateUtils.convertDateToString(new Date());
                Date beginTime = DateUtils.convertStringToDate("yyyy-MM-dd HH:mm", nowDateStr + " " + timeSlot[timeSlot.length - 1]);
                String tradingTime = optionTradingGoods.getTradingTime().substring(0, optionTradingGoods.getTradingTime().length() - 5);
                optionTradingGoods.setTradingTime(tradingTime + DateUtils.parseToDateTimeStr(DateUtils.addMinute(beginTime, 5)).substring(11, 16));
                String jsonObject = JSONObject.toJSONString(optionTradingGoods);
                redisTemplate.opsForValue().set(Constant.TRADE_DATE_INFO + optionTradingGoods.getTradingGoodsCode(), jsonObject);
            }
            Response response=tradeDateCall.checkHoliday(DateUtils.convertDateToString(new Date()));
            String jsonObject = JSONObject.toJSONString(response);
            redisTemplate.opsForValue().set(Constant.DATE_OF_TRANSACTION, jsonObject);

        }catch (Exception e){
            LOGGER.info("getEtfMdInfo Error ..............:", e);
        }
    }
}
